package cn.hengzhu.main_manager.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hengzhu.main_manager.repository.dao.MobileBindKeyMapper;
import cn.hengzhu.main_manager.repository.domain.MobileBindKey;
import cn.hengzhu.main_manager.repository.domain.MobileBindKeyExample;
import cn.hengzhu.main_manager.service.MobileBindKeyService;
import cn.hengzhu.main_manager.utils.AliMsmUtils;

@Service
@Transactional(rollbackFor = Exception.class)
public class MobileBindKeyServiceImpl implements MobileBindKeyService {

	@Autowired
	private MobileBindKeyMapper mobileBindKeyMapper;

	@Override
	public boolean sendMessage(String code, String phoneNumber) throws Exception {
		// 验证码发送失败 使用阿里云短信发送
		if (!AliMsmUtils.sendMessage(phoneNumber, code))
			return false;

		// 存入数据库
		MobileBindKey mbk = new MobileBindKey();
		mbk.setCode(code);
		mbk.setCreateTime(new Date());
		mbk.setStatus((byte) 1);
		mbk.setPhone(phoneNumber);
		mobileBindKeyMapper.insert(mbk);
		return true;
	}

	@Override
	public boolean verifyCode(String code, String phoneNumber, String openId) throws Exception {
		MobileBindKeyExample example = new MobileBindKeyExample();
		example.createCriteria().andPhoneEqualTo(phoneNumber).andCodeEqualTo(code).andStatusEqualTo((byte) 1);

		List<MobileBindKey> mbkes = mobileBindKeyMapper.selectByExample(example);
		if (mbkes.isEmpty()) {
			return false;
		}
		MobileBindKey mbk = mbkes.get(0);
		// 创建时间加上5分钟（过期时间）
		long time = mbk.getCreateTime().getTime() + 1000l * 60l * 5l;
		if (time < new Date().getTime()) { // 过期
			return false;
		}
		mbk.setStatus((byte) 0);// 设置为已使用（无效）
		mbk.setOpenId(openId);//
		mobileBindKeyMapper.updateByPrimaryKey(mbk);
		return true;
	}

}
